//定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTokenStore = defineStore('token', () => {
        //定义状态的内容
        //1.响应式变量
        const token = ref('')
        const remember = ref(JSON.parse(localStorage.getItem('remember') || 'false'))

        //2.定义一个函数,修改token的值
        const setToken = (newToken, rememberMe = false) => {
            token.value = newToken;
            remember.value = rememberMe;

            // 存储remember状态到localStorage
            localStorage.setItem('remember', JSON.stringify(rememberMe));

            // 根据记住状态选择存储方式
            if (rememberMe) {
                localStorage.setItem('token', newToken);
                sessionStorage.removeItem('token');
            } else {
                sessionStorage.setItem('token', newToken);
                localStorage.removeItem('token');
            }
        }

        //3.函数,移除token的值
        const removeToken = () => {
            token.value = '';
            remember.value = false;
            localStorage.removeItem('token');
            sessionStorage.removeItem('token');
            localStorage.removeItem('remember');
        }

        //4.初始化时从存储中加载token
        const initToken = () => {
            const rememberStatus = JSON.parse(localStorage.getItem('remember') || 'false');
            remember.value = rememberStatus;

            if (rememberStatus) {
                token.value = localStorage.getItem('token') || '';
            } else {
                token.value = sessionStorage.getItem('token') || '';
            }
        }

        // 初始化token
        initToken();

        //5.返回值
        return {
            token,
            remember,
            setToken,
            removeToken,
            initToken
        }
    },
// 禁用自动持久化，我们手动管理
    {
        persist: false
    })